package com.tju.resource.business.tb_impl_order.report;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tju.resource.business.tb_impl_order.TbImplOrderService;
import com.tju.resource.mapper.TbImplOrderMapper;
import com.tju.resource.mapper.TbProdPlanMapper;
import com.tju.resource.model.TbImplOrder;
import com.tju.resource.model.TbProdPlan;
import com.tju.resource.result.Result;
import com.tju.resource.result.ResultEnum;
import com.tju.resource.result.ResultUtil;
import com.tju.resource.result.SimpleXls;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.tju.resource.tool.tool.ValueUtil.*;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TbImplReportOrderServiceImpl extends ServiceImpl<TbImplOrderMapper, TbImplOrder>
        implements TbImplReportOrderService {

    private static final String baseXlsPath = TbImplReportOrderServiceImpl.class.getResource("/res/xlsTemplate/TbImplOrder").toString();

    @Autowired
    private TbImplOrderService tbImplOrderService;

    @Autowired
    private TbProdPlanMapper prodPlanMapper;

    @Override
    public boolean REPO_DAILY(JSONObject data, OutputStream out) {
        String file = baseXlsPath + "/HY_RP_Daily_PD.xls";
        InputStream inputStream = TbImplReportOrderServiceImpl.class.getResourceAsStream("/res/xlsTemplate/TbImplOrder/HY_RP_Daily_PD.xls");
        boolean exist = FileUtil.exist(file);

        if (!exist && !file.contains("jar:")) {
            return false;
        } else {
            try {
                Map<String, String> cParams = new HashMap<>();
                Result<Object> objectResult;
                JSONArray list;
                JSONArray dataList = new JSONArray();
                List<Long> ppIds = new ArrayList<>();
                List<TbProdPlan> ppList = null;

                cParams.put("userName", data.getStr("userName"));
                cParams.put("beginDate", data.getStr("beginDate"));
                cParams.put("finishDate", data.getStr("finishDate"));
                cParams.put("page", "1");
                cParams.put("limit", "99999");

                objectResult = tbImplOrderService.selectTbImplOrder(cParams);
                list = JSONUtil.parseArray(objectResult.getData());

                if (list.size() > 0) {
                    list.forEach(v -> ppIds.add(JSONUtil.parseObj(v).getLong("ppId")));
                    ppList = prodPlanMapper.getPpByIds(new HashMap<>(), ppIds);
                }

                List<TbProdPlan> finalPpList = ppList;
                list.forEach(v -> {
                    JSONObject vData = JSONUtil.parseObj(v);
                    JSONObject fData = new JSONObject();

                    fData.putOnce("day", DateUtil.format(vData.getDate("createTime"), "MM/dd"));
                    fData.putOnce("mechNo", vData.getStr("mechNo"));
                    fData.putOnce("color", vData.getStr("color"));
                    fData.putOnce("holeNum", vData.getStr("holes"));
                    fData.putOnce("pcsNum", vData.getStr("rated"));
                    fData.putOnce("prNum", intOrZero(vData.getInt("scrap")) + intOrZero(vData.getInt("quality")) + intOrZero(vData.getInt("backFix")));
                    fData.putOnce("goodNum", vData.getInt("quality"));
                    fData.putOnce("onTime", DateUtil.format(vData.getDate("onTime"), "HH:mm"));
                    fData.putOnce("endTime", DateUtil.format(vData.getDate("endTime"), "HH:mm"));
                    fData.putOnce("goodRate", String.format("%.0f", (douOrZero(fData.getDouble("goodNum")) / douOrZero(fData.getDouble("prNum"))) * 100.0));
                    fData.putOnce("prodBy", strOrEmp(vData.getStr("createBy")));
                    fData.putOnce("scrapNum", vData.getInt("scrap"));
                    fData.putOnce("scrapReason", vData.getStr("scrapRea"));
                    fData.putOnce("remark", vData.getStr("remark"));
                    if (null != finalPpList) {
                        finalPpList.forEach(obj -> {
                            if (obj.getId().equals(vData.getLong("ppId"))) {
                                fData.putOnce("matlName", obj.getMatlName());
                                fData.putOnce("unitTh", obj.getWorkTime());
                            }
                        });
                    }

                    dataList.add(fData);
                });

                data.remove("list");
                data.putOnce("list", dataList);

                if (file.indexOf("jar:") == 0) {
                    SimpleXls.fillTemplate(file, inputStream, data, out);
                } else {
                    SimpleXls.fillTemplate(FileUtil.file(file).getAbsolutePath(), data, out);
                }

                return true;
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    out.write(ResultUtil.error(ResultEnum.UNKONW_ERROR, "could down excel file, cause: " + e.toString()).toString().getBytes());
                } catch (Exception e1) {
                    return false;
                }
                return false;
            }
        }

    }

    @Override
    public boolean REPO_SALARY(JSONObject data, OutputStream out) {
        String file = baseXlsPath + "/HY_RP_Daily_PD_SY.xls";
        InputStream inputStream = TbImplReportOrderServiceImpl.class.getResourceAsStream("/res/xlsTemplate/TbImplOrder/HY_RP_Daily_PD.xls");
        boolean exist = FileUtil.exist(file);

        if (!exist && !file.contains("jar:")) {
            return false;
        } else {
            try {
                Map<String, String> cParams = new HashMap<>();
                Result<Object> objectResult;
                JSONArray list;
                JSONArray dataList = new JSONArray();
                List<Long> ppIds = new ArrayList<>();
                List<TbProdPlan> ppList;

                cParams.put("userName", data.getStr("userName"));
                cParams.put("beginDate", data.getStr("beginDate"));
                cParams.put("finishDate", data.getStr("finishDate"));
                cParams.put("page", "1");
                cParams.put("limit", "99999");

                objectResult = tbImplOrderService.selectTbImplOrder(cParams);
                list = JSONUtil.parseArray(objectResult.getData());

                list.forEach(v -> ppIds.add(JSONUtil.parseObj(v).getLong("ppId")));
                ppList = prodPlanMapper.getPpByIds(new HashMap<>(), ppIds);

                list.forEach(v -> {
                    JSONObject vData = JSONUtil.parseObj(v);
                    JSONObject fData = new JSONObject();

                    fData.putOnce("day", DateUtil.format(vData.getDate("createTime"), "MM/dd"));
                    fData.putOnce("mechNo", vData.getStr("mechNo"));
                    fData.putOnce("color", vData.getStr("color"));
                    fData.putOnce("holeNum", vData.getStr("holes"));
                    fData.putOnce("pcsNum", vData.getStr("rated"));
                    fData.putOnce("nums", intOrZero(vData.getInt("scrap")) + intOrZero(vData.getInt("quality")) + intOrZero(vData.getInt("backFix")));
                    fData.putOnce("goodNums", vData.getInt("quality"));
                    fData.putOnce("onTime", DateUtil.format(vData.getDate("onTime"), "HH:mm"));
                    fData.putOnce("endTime", DateUtil.format(vData.getDate("endTime"), "HH:mm"));
                    fData.putOnce("goodRate", String.format("%.0f", (douOrZero(fData.getDouble("goodNums")) / douOrZero(fData.getDouble("nums"))) * 100.0));
                    fData.putOnce("workBy", vData.getStr("createBy"));
                    fData.putOnce("scrapNum", vData.getInt("scrap"));
                    fData.putOnce("scrapReason", vData.getStr("scrapRea"));
                    fData.putOnce("remark", vData.getStr("remark"));
                    ppList.forEach(obj -> {
                        if (obj.getId().equals(vData.getLong("ppId"))) {
                            fData.putOnce("matlName", obj.getMatlName());
                            fData.putOnce("rt", obj.getWorkTime());
                            fData.putOnce("mv", obj.getMatlVal());
                            fData.putOnce("salary", douOrZero(obj.getMatlVal()) * douOrZero(vData.getDouble("quality")));
                        }
                    });

                    dataList.add(fData);
                });

                data.remove("list");
                data.putOnce("list", dataList);

                if (file.indexOf("jar:") == 0) {
                    SimpleXls.fillTemplate(FileUtil.file(file).getAbsolutePath(), inputStream, data, out);
                } else {
                    SimpleXls.fillTemplate(FileUtil.file(file).getAbsolutePath(), data, out);
                }

                return true;
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    out.write(ResultUtil.error(ResultEnum.UNKONW_ERROR, "could down excel file, cause: " + e.toString()).toString().getBytes());
                } catch (Exception e1) {
                    return false;
                }
                return false;
            }
        }
    }

    @Override
    public boolean REPO_MONTH_SALARY(JSONObject data, OutputStream out) {
        return false;
    }
}
